import { createWorkDir, deleteWorkDir } from "../workDir/index.js";
import { parseProject } from "../parseProject/index.js";
import { generateLock } from "../generateLock/index.js";
import { audit } from "../audit/index.js";
import { render } from '../render/index.js';
import fs from 'fs';
import { getTime } from "../common/utils.js";
import path from 'path'

 async function main(projectRoot, savePath) {
  try {
    // 1. 创建工作目录
    const workDir = await createWorkDir();
    // 2. 解析项目，向工作目录添加pacakge.json
    const packageJson = await parseProject(projectRoot);
    // 3. 生成lock文件
    await generateLock(workDir, packageJson);
    // 4. 对工作目录进行审计
    console.log('🔍 开始审计');
    const auditResult = await audit(workDir, packageJson);
    // 5. 渲染审计结果
    const renderedResult = await render(auditResult, packageJson);
    // await deleteWorkDir(workDir);
    // 保存报告
    const reportPath = savePath || path.join(process.cwd(), `report/result_${getTime()}.md`);
    const reportDir = path.dirname(reportPath);
    await fs.promises.mkdir(reportDir, { recursive: true });
    await fs.promises.writeFile(reportPath, renderedResult);
    console.log('✅ 审计完成!');
    console.log(`📄 报告位置: ${reportPath}`);
    console.log(`📈 漏洞统计: ${auditResult.summary.total} 个漏洞`);
  } catch (error) {
    console.log('❌ 审计失败:', error.message);
    throw error;
  }
}

// main('D:/2025Code/ai-serve/mcp/use-sdk');
main('https://github.com/facebook/react');

export default main